package com.example.myapplication2;

import android.app.PictureInPictureParams;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Build;
import android.util.Rational;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class ApplyPictureInPictureActivity extends AppCompatActivity {

    private DesktopRecevier desktopRecevier;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_picture_in_picture);
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        desktopRecevier = new DesktopRecevier();
        registerReceiver(desktopRecevier,intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(desktopRecevier);
    }

    @Override
    public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode, Configuration newConfig) {
        super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
        if (isInPictureInPictureMode){
            System.out.println("进入画中画模式");
        }else {
            System.out.println("退出画中画模式");
        }
    }

    public class DesktopRecevier extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String reason = intent.getStringExtra("reason");
            if (reason!=null&&(reason.equals("homekey")||reason.equals("recentapps"))){
                if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
                    //构建画中画模式
                    PictureInPictureParams.Builder builder = new PictureInPictureParams.Builder();
                    //设置宽高比例
                    Rational rational = new Rational(10, 5);
                    builder.setAspectRatio(rational);
                    //进入画中画
                    enterPictureInPictureMode(builder.build());
                }
            }
        }
    }
}